#!/bin/bash

# https://cr.console.aliyun.com/cn-hangzhou/instance/credentials

# 任一命令失败则立即退出脚本
set -e

# 检查并加载本地配置文件
if [ -f ".local-config" ]; then
  source .local-config
else
  echo "❌ 错误：.local-config 文件不存在！"
  echo "请创建该文件并设置以下变量："
  echo "  ALIYUN_USERNAME     # 阿里云容器镜像服务用户名"
  echo "  ALIYUN_PASSWORD     # 阿里云容器镜像服务密码（建议使用访问凭证）"
  echo "  ALIYUN_REGISTRY     # 阿里云容器镜像仓库地址（例如：registry.cn-hangzhou.aliyuncs.com）"
  echo "  NAMESPACE           # 命名空间（通常为阿里云账号或子账号）"
  echo "  IMAGE_NAME          # 镜像名称"
  echo "  IMAGE_TAG           # 镜像标签"
  exit 1
fi

# 验证必需的变量是否已设置
required_vars=(
  ALIYUN_USERNAME
  ALIYUN_PASSWORD
  ALIYUN_REGISTRY
  NAMESPACE
  IMAGE_NAME
  IMAGE_TAG
)

for var in "${required_vars[@]}"; do
  if [ -z "${!var}" ]; then
    echo "❌ 错误：变量 $var 未在 .local-config 中设置！"
    exit 1
  fi
done

# 登录阿里云 Docker 镜像仓库
echo "🔐 正在登录阿里云 Docker 镜像仓库..."
docker login --username="${ALIYUN_USERNAME}" --password="${ALIYUN_PASSWORD}" "${ALIYUN_REGISTRY}"

# 为 Docker 镜像打标签
echo "🏷️  正在为 Docker 镜像打标签..."
docker tag "${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}" "${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"

# 将 Docker 镜像推送到阿里云
echo "🚀 正在将 Docker 镜像推送到阿里云..."
docker push "${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"

echo "✅ Docker 镜像已成功推送！"

echo "📥 拉取命令：docker pull ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"
echo "🔄 本地重命名命令（如需）：docker tag ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} ${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"

# 退出阿里云 Docker 镜像仓库登录
echo "🔓 正在退出阿里云 Docker 镜像仓库登录..."
docker logout "${ALIYUN_REGISTRY}"

echo "✨ 操作完成！"